package main

import (
	"flag"
	"fmt"
	"net"
	"sync"
	"time"
)

func main() {
	ports := []int{}
	hostname := flag.String("hostname", "google.com", "hostname to test")
	portStart := flag.Int("port-start", 80, "port-start")
	portEnd := flag.Int("port-end", 100, "port-end")
	timeout := flag.Duration("timeout", time.Millisecond*200, "timeout")
	flag.Parse()

	mutex := &sync.Mutex{}
	wg := &sync.WaitGroup{}
	for port := *portStart; port < *portEnd; port++ {
		wg.Add(1)
		port := port
		go func(p int) {
			open := isOpen(*hostname, p, *timeout)
			if open {
				mutex.Lock()
				ports = append(ports, p)
				mutex.Unlock()
			}
			wg.Done()
		}(port)

	}
	wg.Wait()
	fmt.Println("ports:", ports)

}

func isOpen(host string, port int, timeout time.Duration) bool {
	url := fmt.Sprintf("%s:%d", host, port)
	fmt.Printf("正在连接 %s\n", url)
	conn, err := net.DialTimeout("tcp", url, timeout)
	if err == nil {
		conn.Close()
		return true
	}
	return false
}
